package com.gsoe.auth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.gsoe.auth.utils.FileUtils;
import com.gsoe.auth.mapper.ResourceMapper;

import com.gsoe.auth.po.Resource;
import com.gsoe.auth.service.ResourceService;

import com.gsoe.auth.service.UserInfoService;
import com.gsoe.base.exception.UserException;
import io.minio.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 班级资源表 服务实现类
 * </p>
 *
 * @author xiaoma
 * @since 2024-12-15
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {
    @Autowired
    MinioClient minioClient;

    @Autowired
    UserInfoService userInfoService;
    @Override
    public String uploadAvatar(MultipartFile multipartFile) {
        if(StringUtils.isEmpty(multipartFile.getOriginalFilename()))throw new UserException("文件解析失败，文件名为空");
        String fileSuffix = FileUtils.getFileSuffix(multipartFile.getOriginalFilename());
        boolean b = FileUtils.checkImageSuffix(fileSuffix);
        if(!b)throw new UserException("不支持该格式文件");

        String filePathByFile;
        try {
            filePathByFile = FileUtils.getFilePathByFile(multipartFile);
        }catch (Exception e){
            throw new UserException(e.getMessage());
        }
        uploadToMinio(multipartFile,"avatar",filePathByFile);

        return "avatar"+filePathByFile;
    }



    private void uploadToMinio(MultipartFile multipartFile,String bucketName,String filePathByFile) {

        try {

            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                    .object(filePathByFile)
                    .build());
        }catch (Exception e){
            e.printStackTrace();
            throw new UserException("updateAvatar:上传失败:"+e.getMessage());
        }
    }
}
